package com.example.demo.controller;

import com.example.demo.model.Teacher;
import com.example.demo.model.Teacher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("teacher")
public class TeacherController {
    private static List<Teacher> teacherList = new ArrayList<>();
    static {
        Teacher t1 = new Teacher();
        t1.setId(1);
        t1.setName("Tom");
        teacherList.add(t1);
        Teacher t2 = new Teacher();
        t2.setId(2);
        t2.setName("Jerry");
        teacherList.add(t2);
    }
    @RequestMapping("list")
    public String list(ModelMap modelMap){
        modelMap.put("teacherList", teacherList);
        return "teacher/list";
    }
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable Integer id) {
        teacherList.remove(id - 1);
        return "redirect:/teacher/list";
    }
    @RequestMapping("save")
    public String save(Teacher t) {
        t.setId(teacherList.size() + 1);
        teacherList.add(t);
        return "redirect:/teacher/list";
    }
    @RequestMapping("edit/{id}")
    public String edit(@PathVariable Integer id, ModelMap map) {
        Teacher t = teacherList.get(id - 1);
        map.put("teacher", t);
        return "teacher/edit";
    }
    @RequestMapping("update")
    public String update(Teacher t) {
        for (Teacher teacher: teacherList) {
            if (teacher.getId().equals(t.getId())) {
                teacher.setName(t.getName());
            }
        }
        return "redirect:/teacher/list";
    }
}

